package com.xydtech.common.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 创建时间：2022/7/12 9:30
 * 项目名称：xydtech
 * @author JHON
 * @version 1.0
 * @since JDK 1.8.0_201
 * 文件名称：WordTemplateUtil
 * 类说明：文档处理类

 */

public class WordTemplateUtil {

    /*从word模板 渲染参数 获取word文档
     * template 模板文件 params 参数 outputStream 输出流,
     */
    public static void wordRenderAndGetFromWordTemplate(File template, Map params, OutputStream outputStream) throws Exception {
        FileInputStream inputStream = new FileInputStream(template);
        XWPFDocument templateDoc = new XWPFDocument(inputStream);

        produce(templateDoc, params);
        templateDoc.write(outputStream);
    }

    /* 处理参数 生成doc */
    public static void produce(XWPFDocument templateDoc, Map params) {
        Iterator iterator = templateDoc.getParagraphsIterator();
        while (iterator.hasNext()) {
            XWPFParagraph next = (XWPFParagraph) iterator.next();
            if (next.isEmpty() || !match(next.getParagraphText())) {
                continue;
            }
            next.getRuns().forEach(
                    run -> setNewTextForRun(run, params)
            );
        }
    }

    /*
     * 正则匹配 返回 matcher
     * */
    public static Matcher matcher(String text) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)}", Pattern.CASE_INSENSITIVE);
        return pattern.matcher(text);
    }

    /*
     * 判定是否包匹配
     * */
    public static boolean match(String text) {
        Matcher matcher = matcher(text);
        return matcher.find();
    }

    /*
     * 替换参数 设置新参数
     * */
    public static void setNewTextForRun(XWPFRun run, Map params) {
        List<CTText> ctTexts = run.getCTR().getTList();
        ctTexts.forEach(
                ctText -> {
                    String text = ctText.getStringValue();
                    Matcher matcher = matcher(text);
                    while (matcher.find()) {
                        String group = matcher.group();
                        if (group.contains(" ")) {
                            try {
                                throw new Exception("${}表达式不能包含空格");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        String name = group.substring(2, group.length() - 1);
                        String value = params.get(name).toString();
                        value = value == null ? "" : value;
                        if (text.equals(group)) {
                            text = value;
                        } else {
                            //转义
                            String[] parts = text.split("\\$\\{" + name + "}");
                            //length=1 分前后 设置参数值
                            if (parts.length == 1) {
                                String part = parts[0];
                                text = text.indexOf(part) == 0 ? (part + value) : (value + part);
                            } else {
                                text = StringUtils.join(parts, value);
                            }
                        }
                    }
                    ctText.setStringValue(text);
                }
        );
    }
}